package com.higgins.lawapp.client.settings.components;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.ListBox;
import com.higgins.lawapp.client.listeners.DataSourceDTOListBoxListener;
import com.higgins.lawapp.client.listeners.DataSourceDTOsListener;
import com.higgins.lawapp.client.settings.dataModel.DataSourceDTO;
import com.higgins.lawapp.client.settings.model.DataSourceModel;
import com.higgins.lawapp.client.settings.presenter.DataSourcePresenter;


public class DataSourceListBox extends ListBox implements ChangeHandler, DataSourceDTOsListener	{
	private List<DataSourceDTOListBoxListener> dataSourceDTOListBoxListeners 
			=	new ArrayList<DataSourceDTOListBoxListener>();
	private List<DataSourceDTO> dataSourceDTOs;
	private DataSourcePresenter dataSourcePresenter;
	private DataSourceModel dataSourceModel;
	
	public DataSourceListBox(DataSourcePresenter dataSourcePresenter)	 {
		setVisibleItemCount(1);
		this.dataSourcePresenter = dataSourcePresenter;
		this.dataSourceModel = dataSourcePresenter.getDataSourceMode();;
		dataSourceModel.addDataSourceDTOsListener(this);
		dataSourceModel.retrieveDataSourceDTOs();
		this.addChangeHandler(this);
	}
	public void addDataSourceListBoxListener(DataSourceDTOListBoxListener dataSourceDTOListBoxListener)	{
		dataSourceDTOListBoxListeners.add(dataSourceDTOListBoxListener);
	}
	public void setDataSourceDTOs(List<DataSourceDTO> dataSourceDTOs)	{
		this.dataSourceDTOs = dataSourceDTOs;
		if (dataSourceDTOs!=null)
			update();
	}
	public void update()	{
		this.clear();
		addItem("None");
		Iterator<DataSourceDTO> iterator = dataSourceDTOs.iterator();
		while (iterator.hasNext())	{
			DataSourceDTO dataSourceDTO = iterator.next();
			addItem(dataSourceDTO.getDataSourceName());
		}
	}
	@Override
	public void onChange(ChangeEvent event) {
		DataSourceDTO dataSourceDTOSelected = null;
		if (getSelectedIndex() == 0)	{
			
		}
		else	{
			dataSourceDTOSelected = dataSourceDTOs.get(getSelectedIndex() - 1);
		}
		Iterator<DataSourceDTOListBoxListener> iterator = dataSourceDTOListBoxListeners.iterator();
		while (iterator.hasNext())	{
			DataSourceDTOListBoxListener dataSourceDTOSelectedListener=iterator.next();
			dataSourceDTOSelectedListener.setDataSourceDTOSelected(dataSourceDTOSelected, getSelectedIndex()-1);
		}
		
	}
}
